package com.gzdh.device.comm.util;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayConstants;
import com.gzdh.device.comm.vo.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.github.wxpay.sdk.WXPayUtil.HMACSHA256;

public class ThirSignUtil {

    public static boolean thirSign(HttpServletRequest request) {
        try {
            Map<String, String> map = new HashMap<>();
            Map<String, String[]> reqMap = request.getParameterMap();
            reqMap.forEach((t, u) -> {
                map.put(t, u[0]);
            });
            String sign = request.getParameter("sign");

            if (sign == null) {

                return false;
            }
            if (!isSignatureValid(map, "123456789987654321")) {

                return false;
            }
            String times = request.getParameter("urlTime");
            Long sysTime = System.currentTimeMillis();
            if (sysTime - Long.valueOf(times) > 10000) {

                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        if (!data.containsKey(WXPayConstants.FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (!data.get(k).trim().isEmpty()) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        return HMACSHA256(sb.toString(), key);
    }
}
